<?php
/**
 * Project: Recipe
 * File: UserAction.class.php
 * Author: Xnfy520@gmail.com
 * Date: 12-5-28
 * Time: 上午10:41
 */

class UserAction extends CommonAction{

	function index(){
		if(isset($_SESSION['username']) && !empty($_SESSION['username'])){
			$user = M('User');

			$userinfo = $user->find($_SESSION['userid']);
			$datas = array('logindate'=>time(),'loginip'=>$_SERVER['REMOTE_ADDR']);
			$user->where('id='.$_SESSION['userid'])->setField($datas);

			$this->assign('userinfo',$userinfo);
			$this->display('profile');
		}else{
			$this->redirect('Index/index');
		}
	}

	/**
	 *用户头像上传
	 */
	function uploads(){
		import("ORG.Net.emit_upload");
		import("ORG.Util.emit_image");
		$upload = new upload(array("filepath"=>"./Public/Content/tmp","allowtype"=>array('gif','png','jpg'),"israndname"=>true,"maxsize"=>2000000));
		if($upload->uploadfiles('pic')){
			$img = new image("./Public/Content/tmp");
			$imgname =  $upload->getnewname();
			if($img->cut($imgname)){
				$img->thumb($imgname, 130, 130);
			}
			echo $upload->getnewname();
		}else{
			echo $upload->geterrormsg();
		}
	}

	function logout(){
		if(isset($_SESSION['username']) || isset($_COOKIE['username'])) {
			unset($_SESSION);
			session_destroy();
			$this->success('Exit success', __ROOT__);
		}else {
			$this->error('Has Been Out',__APP__.'Index/index');
		}
	}

	function login(){

		if(isset($_SESSION['username']) && isset($_SESSION['userid']) && isset($_SESSION['userrole'])){
			$this->redirect('/Index/index');
		}else{
			if(isset($_POST['email']) && isset($_POST['password'])){
				if(!empty($_POST['email']) && !empty($_POST['password'])){
					$user = D('User');
					$map['email'] = $_POST['email'];
					$userinfo = $user->relation(true)->where($map)->find();
					if(md5($_POST['password'])==$userinfo['password']){
						if($userinfo['status']==1){
							unset($_SESSION['username']);
							unset($_SESSION['userid']);
							unset($_SESSION['userrole']);
							$_SESSION['username'] = $userinfo['username'];
							$_SESSION['userid'] = $userinfo['id'];
							$_SESSION['userrole'] = $userinfo['roleuser']['roleid'];
							$this->success('登录成功',__APP__.'/User/index');
						}else{
							$this->error('该用户不存在或未激活');
						}
					}else{
						$this->error('用户名或密码不正确');
					}
				}else{
					$this->error('异常操作');
				}
			}else{
				$this->error('异常操作');
			}
		}

	}

	function active(){

		if(isset($_GET['action']) && $_GET['action']=='ok'){
			if(isset($_GET['uniqid']) && !empty($_GET['uniqid'])){
				if(isset($_GET['uid']) && !empty($_GET['uid'])){
					$user = M('User');
					$userinfo = $user->find($_GET['uid']);
					if(empty($userinfo['uniqid'])){
						$this->error('该用户不存在,或已经激活');
					}else{
						if($_GET['uniqid']!=$userinfo['uniqid']){
							$this->error('非法操作');
						}else{
							$datas = array('uniqid'=>'','status'=>1);
							$user->where('id='.$_GET['uid'])->setField($datas);

							if(C('ENABLE')==1){

								import("ORG.Net.phpmailer");
								$mail = new PHPMailer(true);
								$mail->IsSMTP();
								$mail->SMTPAuth   = true;
								$mail->Port       = C('EMAILPORT');
								$mail->Host       =C('EMAILSERVER');
								$mail->Username   = C('FROMEMAIL');
								$mail->Password   = C('PASSWORD');
								$mail->AddReplyTo(C('FROMEMAIL'),C('FROMEMAILALIAS'));
								$mail->From       = C('FROMEMAIL');
								$mail->FromName   = C('FROMEMAILALIAS');
								$mail->IsHTML(true);
								$mail->AddAddress($userinfo['email']);
								$setmail = M('SetEmail');
									$successmail = $setmail->find(2);
									if($successmail['status']==1){
										$mail->Subject  = $successmail['title'];
										$body = str_replace('%username%', $userinfo['username'], $successmail['content']);
										$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
									}
								$mail->MsgHTML($body);
								$mail->Send();
							}

							$this->success('激活成功',__APP__.'/Index/login');
						}
					}
				}
			}else{
				$this->error('异常操作');
			}
		}else{
			$this->error('异常操作');
		}
	}

	function change(){
		if(isset($_GET['modify']) && isset($_GET['time'])){
			if(!empty($_GET['modify']) && !empty($_GET['time'])){
				$user = M('User');
				$userinfo = $user->getByEmail($_GET['modify']);
				echo $_GET['time'];
				echo '<br />';
				echo md5($userinfo['changetime']);
				if($_GET['time']==md5($userinfo['changetime'])){
					if(time()-$userinfo['changetime'] > 60*60*24){
						$this->error('链接已经过期');
					}else{
						$this->assign('userinfo',$userinfo);
						$this->display('password');
					}
				}else{
					$this->error('异常操作');
				}
			}else{
				$this->error('异常操作');
			}
		}else{
			$this->error('异常操作');
		}
	}

	function changepassword(){
		if(isset($_POST['id']) && isset($_POST['email']) && isset($_POST['password'])){
			if(!empty($_POST['id']) && !empty($_POST['email']) && !empty($_POST['password'])){
				$user = M('User');
				$userinfo = $user->where('email='.$_POST['email'])->find($_POST['id']);
				if(!empty($userinfo)){
					$data['password'] = md5($_POST['password']);
					$map['id'] = $_POST['id'];
					$map['email'] = $_POST['email'];
					if($user->where($map)->save($data)){
						$this->success('密码修改成功',__APP__.'/Index/login');
					}else{
						$this->error('密码修改失败');
					}
				}else{
					$this->error('异常操作');
				}
			}else{
				$this->error('异常操作');
			}
		}else{
			$this->error('异常操作');
		}
	}

	function favourite(){
		if(isset($_GET['type']) && !empty($_GET['type'])){
			if(isset($_SESSION['username']) && isset($_SESSION['userid'])){
				if(!empty($_SESSION['username']) && !empty($_SESSION['userid'])){
					$user = M('User');
					$favourite = D('RecipeFavourite');
					import("ORG.Util.emit_page");
					$userinfo = $user->find($_SESSION['userid']);
					if(empty($userinfo)){
						$this->redirect('Index/index');
					}
					$this->assign('userinfo',$userinfo);

					$recipemap['founder'] = $_SESSION['userid'];
					$recipemap['sectionid'] = $_GET['type'];

					$count = $favourite->where($recipemap)->count();

					$page = new page($count, 10);
					$recipeinfo = $favourite->relation(true)->limit($page->setlimit())->where($recipemap)->select();

					$this->assign('recipeinfo', $recipeinfo);
					$this->assign('fpage', $page->fpage(array(5,6,7)));
					$this->display();
				}else{
					$this->error('异常操作');
				}
			}else{
				$this->error('异常操作');
			}
		}else{
			$this->error('异常操作');
		}
	}

	function article(){
		if(isset($_GET['type']) && !empty($_GET['type'])){
			if(isset($_SESSION['username']) && isset($_SESSION['userid'])){
				if(!empty($_SESSION['username']) && !empty($_SESSION['userid'])){
					$user = M('User');
					import("ORG.Util.emit_page");
					$userinfo = $user->find($_SESSION['userid']);
					if(empty($userinfo)){
						$this->redirect('Index/index');
					}
					$this->assign('userinfo',$userinfo);
					$recipemap['founder'] = $_SESSION['userid'];
					$recipemap['recipetypeid'] = $_GET['type'];
					switch($_GET['type']){
						case 1:
							$recipe = M('RecipeArticle');
							$count = $recipe->where($recipemap)->count();
							$page = new page($count, 10);
							$recipeinfo = $recipe->limit($page->setlimit())->where($recipemap)->select();
							break;
						case 2 :
							$special = M('SpecialArticle');
							$count = $special->where($recipemap)->count();
							$page = new page($count, 10);
							$recipeinfo = $special->limit($page->setlimit())->where($recipemap)->select();
							break;
						case 3 :
							$sauce = M('SauceArticle');
							$count = $sauce->where($recipemap)->count();
							$page = new page($count, 10);
							$recipeinfo = $sauce->limit($page->setlimit())->where($recipemap)->select();
							break;
						case 4 :
							$kitchen = M('KitchenArticle');
							$count = $kitchen->where('founder='.$_SESSION['userid'])->count();
							$page = new page($count, 10);
							$recipeinfo = $kitchen->limit($page->setlimit())->where('founder='.$_SESSION['userid'])->select();
							break;
					}
					$this->assign('recipeinfo', $recipeinfo);
					$this->assign('fpage', $page->fpage(array(5,6,7)));
					$this->display();
				}else{
					$this->error('异常操作');
				}
			}else{
				$this->error('异常操作');
			}
		}else{
			$this->error('异常操作');
		}

	}

	public function insert(){

		$user = D('User');

		if($data = $user->create()){

			$roleuser = M('RoleUser');

			if($userid = $user->add($data)){

				$roleuserdata['roleid'] = $_POST['roleid'];
				$roleuserdata['userid'] = $userid;
				$roleuser->add($roleuserdata);

				if(C('ENABLE')==1){

					import("ORG.Net.phpmailer");
					$mail = new PHPMailer(true);
					$mail->IsSMTP();
					$mail->SMTPAuth   = true;
					$mail->Port       = C('EMAILPORT');
					$mail->Host       =C('EMAILSERVER');
					$mail->Username   = C('FROMEMAIL');
					$mail->Password   = C('PASSWORD');
					$mail->AddReplyTo(C('FROMEMAIL'),C('FROMEMAILALIAS'));
					$mail->From       = C('FROMEMAIL');
					$mail->FromName   = C('FROMEMAILALIAS');
					$mail->IsHTML(true);
					$mail->AddAddress($data['email']);

					$setmail = M('SetEmail');
//echo '<a href="http://www.meishij.com/User/active/action/ok/uniqid/'.$data['uniqid'].'">http://www.meishij.com/User/active/action/ok/uniqid/'.$data['uniqid'].'</a>';
					if($data['status']==0){
						$activemail = $setmail->find(1);

						if($activemail['status']==1){
							$mail->Subject  = $activemail['title'];
							$body = str_replace('%username%', $data['username'], $activemail['content']);
							$body = str_replace('%activeurl%', '<a target="_blank" href="http://localhost'.__APP__.'/User/active/action/ok/uniqid/'.$data['uniqid'].'/uid/'.$userid.'">http://localhost'.__APP__.'/User/active/action/ok/uniqid/'.$data['uniqid'].'/uid/'.$userid.'</a>', $body);
							$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
						}
					}else{
						$successmail = $setmail->find(2);
						if($successmail['status']==1){
							$mail->Subject  = $successmail['title'];
							$body = str_replace('%username%', $data['username'], $successmail['content']);
							$body = str_replace('%date%', date('Y-m-d H:i:s'), $body);
						}
					}
					$mail->MsgHTML($body);
					$mail->Send();
				}
			//	$this->assign('waitSecond',500);
				$this->success('添加用户成功', __APP__.'/Index/login');
			}else{
				$this->error('添加用户失败');
			}
		}else{
			$this->error($user->getError(), __APP__.'/Index/join');
		}

	}


	/**
	 * 修改用户信息
	 */
	function update(){
		if(isset($_POST['id']) && !empty($_POST['id'])){
			$tmpdir = './Public/Content/tmp/';
			$srcdir = './Public/Content/User/';

			$user = M('User');
			$userinfo = $user->find($_POST['id']);

			if($data = $user->create()){

				if(empty($data['password'])){

					unset($data['password']);
					$user->save($data);
					if($data['gravatar']!=$userinfo['gravatar']){
						unlink($srcdir.$userinfo['gravatar']);
						copy($tmpdir.$data['gravatar'], $srcdir.$data['gravatar']);
						if($dirsrc = opendir($tmpdir)){
							while($files = readdir($dirsrc)){
								if($files!='.' && $files!='..'){
									$pathfile = $tmpdir.$files;
									if(is_file($pathfile)){
										unlink($pathfile);
									}
								}
							}
						}
					}

				}else{

					$data['password'] = md5($data['password']);
					$user->save($data);
					if($data['gravatar']!=$userinfo['gravatar']){
						unlink($srcdir.$userinfo['gravatar']);
						copy($tmpdir.$data['gravatar'], $srcdir.$data['gravatar']);
						if($dirsrc = opendir($tmpdir)){
							while($files = readdir($dirsrc)){
								if($files!='.' && $files!='..'){
									$pathfile = $tmpdir.$files;
									if(is_file($pathfile)){
										unlink($pathfile);
									}
								}
							}
						}
					}
				}

				$this->success('修改用户成功',  __APP__.'/User/index');
			}else{
				$this->error($user->getError());
			}

		}else{
			$this->error('异常操作');
		}

	}

}